<template>
  <div class="log-management">
    <div class="page-header">
      <h2>操作日志</h2>
      <div class="filter-container">
        <el-select v-model="filter.operationType" placeholder="操作类型" clearable style="width: 120px">
          <el-option label="创建" value="CREATE"></el-option>
          <el-option label="更新" value="UPDATE"></el-option>
          <el-option label="删除" value="DELETE"></el-option>
        </el-select>
        <el-input v-model="filter.username" placeholder="用户名" clearable style="width: 150px; margin-left: 10px"></el-input>
        <el-button type="primary" @click="handleFilter" style="margin-left: 10px">筛选</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>

    <!-- Log Table -->
    <el-table :data="logs" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="operationType" label="操作类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="getOperationTypeTag(scope.row.operationType)">{{ scope.row.operationType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operationTime" label="操作时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.operationTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="operatedBy" label="操作人" width="120" />
      <el-table-column label="数据快照" min-width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showSnapshot(scope.row)">查看快照</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Snapshot Dialog -->
    <el-dialog title="数据快照" :visible.sync="snapshotVisible" width="600px">
      <pre class="snapshot-json">{{ formattedSnapshot }}</pre>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'LogManagement',
  data() {
    return {
      logs: [],
      loading: false,
      snapshotVisible: false,
      currentSnapshot: null,
      filter: {
        operationType: '',
        username: ''
      }
    }
  },
  computed: {
    formattedSnapshot() {
      if (!this.currentSnapshot) return ''
      try {
        const obj = JSON.parse(this.currentSnapshot)
        return JSON.stringify(obj, null, 2)
      } catch (e) {
        return this.currentSnapshot
      }
    }
  },
  created() {
    this.fetchLogs()
  },
  methods: {
    // Fetch all logs
    fetchLogs() {
      this.loading = true
      this.$axios.get('/api/logs')
        .then(response => {
          this.logs = response.data
        })
        .catch(error => {
          console.error('Error fetching logs:', error)
          this.$message.error('获取日志列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // Format date
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    },
    
    // Get tag type based on operation type
    getOperationTypeTag(type) {
      switch(type) {
        case 'CREATE': return 'success'
        case 'UPDATE': return 'warning'
        case 'DELETE': return 'danger'
        default: return 'info'
      }
    },
    
    // Show data snapshot
    showSnapshot(row) {
      this.currentSnapshot = row.dataSnapshot
      this.snapshotVisible = true
    },
    
    // Handle filter
    handleFilter() {
      this.loading = true
      
      if (this.filter.operationType && !this.filter.username) {
        // Filter by operation type
        this.$axios.get(`/api/logs/type/${this.filter.operationType}`)
          .then(response => {
            this.logs = response.data
          })
          .catch(error => {
            console.error('Error fetching filtered logs:', error)
            this.$message.error('获取筛选日志失败')
          })
          .finally(() => {
            this.loading = false
          })
      } else if (this.filter.username && !this.filter.operationType) {
        // Filter by username
        this.$axios.get(`/api/logs/username/${this.filter.username}`)
          .then(response => {
            this.logs = response.data
          })
          .catch(error => {
            console.error('Error fetching filtered logs:', error)
            this.$message.error('获取筛选日志失败')
          })
          .finally(() => {
            this.loading = false
          })
      } else if (this.filter.username && this.filter.operationType) {
        // Filter by both (client-side filtering for simplicity)
        this.$axios.get(`/api/logs/username/${this.filter.username}`)
          .then(response => {
            this.logs = response.data.filter(log => 
              log.operationType === this.filter.operationType
            )
          })
          .catch(error => {
            console.error('Error fetching filtered logs:', error)
            this.$message.error('获取筛选日志失败')
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        // No filter, get all
        this.fetchLogs()
      }
    },
    
    // Reset filter
    resetFilter() {
      this.filter.operationType = ''
      this.filter.username = ''
      this.fetchLogs()
    }
  }
}
</script>

<style scoped>
.log-management {
  padding: 0 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.filter-container {
  display: flex;
  align-items: center;
}
.snapshot-json {
  white-space: pre-wrap;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}
</style> 